package cnki.kg.demo;

import cnki.kg.demo.util.Neo4jUtil;
import cnki.kg.demo.util.StringUtil;
import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;

import java.io.*;
import java.util.*;
import java.util.stream.Collectors;


@SpringBootTest
@WebAppConfiguration
public class CreateCtwhDic {

    @Autowired
    Neo4jUtil neo4jUtil;
    @Autowired
    @Qualifier("mysqlJdbcTemplate")
    JdbcTemplate mysqlJdbcTemplate;
    @Test
    public void selet() throws IOException {
        String cyphertotal = "match(n:`zhctwh`)  return count(n)";
        long total = neo4jUtil.GetGraphValue(cyphertotal);
        System.out.println(total);
        Integer pageSize = 500;
        long toatlPage = total / pageSize + ((total % pageSize) == 0 ? 0 : 1);
        HashSet<String> set = new HashSet<>();
        for (Integer pageIndex = 0; pageIndex < toatlPage; pageIndex++) {
            System.out.println(pageIndex);
            String cypher = String.format("match(n:`zhctwh`)  return n skip %s limit %s", pageSize * pageIndex,pageSize);
            List<HashMap<String, Object>> nodes = neo4jUtil.GetGraphNode(cypher);
            for (HashMap<String, Object> node : nodes) {
                String name = node.get("name").toString();
                set.add(name);

                if (node.get("hypernym") != null) {
                    List<String> hy = (List<String>) node.get("hypernym");
                    if (hy.size() > 0) {
                        for (String s : hy) {
                            if(StringUtil.isNotBlank(s)){
                                set.add(s);
                            }
                        }
                    }
                }
                if (node.get("similar") != null) {
                    if(node.get("similar") instanceof List){
                        List<String> sy = (List<String>)  node.get("similar");
                        if (sy.size() > 0) {
                            for (String s : sy) {
                                if(StringUtil.isNotBlank(s)){
                                    set.add(s);
                                }
                            }
                        }
                    }
                   else {
                        System.out.println(node.get("code"));
                    }
                }
            }
        }
        String sql="SELECT CONTENT FROM KG_WORD_ITEM_CTWHCTWH WHERE STATE = 1 ";
        List<Map<String, Object>> mapList = mysqlJdbcTemplate.queryForList(sql);
        if(mapList==null||mapList.size()==0) return;
        for (Map<String, Object> mp : mapList) {
            String content=mp.get("CONTENT")!=null?mp.get("CONTENT").toString():"";
            if(StringUtil.isNotBlank(content)){
                //标点符号分词
                String[] arr=content.split("、|，|。|；|？|！|,|\\.|;|\\[|\\?|!|]|《|》|\\(|\\)|（|）|—|_|-|·| ");
                for (String s : arr) {
                    if(StringUtil.isNotBlank(s)){
                        set.add(s);
                    }
                }
            }
        }
        StringBuilder builder=new StringBuilder();
        if(set!=null&&set.size()>0){
            for (String s : set) {
                String str=String.format("%s\t%s\t%s",s,90000,"n");
                builder.append(str+"\r\n");
            }
        }
        String text=builder.toString();
        String path = "D:\\text\\ctwh.txt";
        File file = new File(path);
        if (!file.exists()) {
            file.getParentFile().mkdirs();
        }
        file.createNewFile();
        OutputStreamWriter fw = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(text);
        bw.flush();
        bw.close();
        fw.close();
    }
    @Test
    public void respairDicSimilar(){
        String cypher = "match(n:`zhctwh`) where  apoc.meta.type(n.similar)='STRING' return n";
        List<HashMap<String, Object>> nodes = neo4jUtil.GetGraphNode(cypher);
        for (HashMap<String, Object> node : nodes) {
            String name = node.get("name").toString();
            System.out.println(name);
            if(node.get("similar")!=null){
                String similar = node.get("similar").toString();
                String[] sarr=similar.split(";",-1);
                List<String> sList=Arrays.asList(sarr);
                List<String> sMap=new ArrayList<>(sList);
                List<String> formatList=sMap.stream().map(n->String.format("'%s'",n.trim())).collect(Collectors.toList());
                String arrStr=String.format("[%s]",String.join(",",formatList));
                System.out.println(arrStr);
                String cypherSql2 = String.format("MATCH (n:`%s`) where n.name='%s' set n.similar=%s ", "zhctwh", name,arrStr);
                neo4jUtil.excuteCypherSql(cypherSql2);
            }
        }
    }
    @Test
    public void mergeCode(){
        String[] arr1=new String[]{"27301","27302"};
        List<String> codeArray1=new ArrayList<>(Arrays.asList(arr1));
        String[] arr2=new String[]{"2730101","2730102","2730201","5042001"};
        List<String> codeArray2=new ArrayList<>(Arrays.asList(arr2));
        List<String> codeArray=getMergeCode(codeArray1,codeArray2);
        System.out.println(codeArray);
    }
    private List<String> getMergeCode(List<String> codeArray,List<String> codeArray2) {
        codeArray = codeArray.stream().distinct().collect(Collectors.toList());
        codeArray2 = codeArray2.stream().distinct().collect(Collectors.toList());
        HashMap<String,List<String>> kv=new HashMap<>();
        List<String> filterCodes = new ArrayList<>();
        for (String firstCode : codeArray) {
            for (String secondCode : codeArray2) {
                if (secondCode.startsWith(firstCode)&&!filterCodes.contains(secondCode)) {
                    filterCodes.add(secondCode);
                }
                if (firstCode.startsWith(secondCode)&&!filterCodes.contains(firstCode)) {
                    filterCodes.add(firstCode);
                }
            }
            kv.put(firstCode,filterCodes);
        }
        return filterCodes;
    }
}
